<template>
  <div class="warehouse-container">
    <h2 class="section-title">制冷剂仓库布局图</h2>
    
    <div class="content-wrapper">
      <div class="layout-container">
        <div class="warehouse-layout">
            <!-- 左侧制冷剂区域 -->
            <div class="refrigerant-area">
              <!-- 顶部架子（11个） -->
              <div class="top-rock">
                <div class="rack-row">
                  <div
                    v-for="(rack, index) in topRacks"
                    :key="'top-' + index"
                    class="rack"
                    @click="selectRack(rack)"
                  >
                    <div class="rack-label">{{ rack.refrigerant_type }}</div>
                    <div class="rack-weight">{{ rack['Refrigerant weight'] }} kg</div>
                  </div>
                </div>
              </div>
              
              <!-- 底部区域 -->
              <div class="bottom-row">
                <!-- 左侧架子（1个） -->
                <div class="left-rock">
                  <div
                    class="rack"
                    @click="selectRack(leftRack)"
                  >
                    <div class="rack-label">{{ leftRack.refrigerant_type }}</div>
                    <div class="rack-weight">{{ leftRack['Refrigerant weight'] }} kg</div>
                  </div>
                </div>
                
                <!-- 底部架子（8个） -->
                <div class="bottom-area">
                  <div class="bottom-road">
                    <h2 class="bottom-road-title">制冷剂仓库</h2>
                  </div>
                  <div class="bottom-rock">
                    <div class="main-door door">大门</div>
                    <div class="rack-row">
                      <div
                        v-for="(rack, index) in bottomRacks"
                        :key="'bottom-' + index"
                        class="rack"
                        @click="selectRack(rack)"
                      >
                        <div class="rack-label">{{ rack.refrigerant_type }}</div>
                        <div class="rack-weight">{{ rack['Refrigerant weight'] }} kg</div>
                      </div>
                    </div>
                    <div class="small-door door">小门</div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 右侧废品库 -->
            <div class="waste-oil-area">
              <h2 class="area-title">废品库</h2>
            </div>
          </div>
        
      </div>
    </div>

    <!-- 编辑重量的对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`制冷剂仓库重量管理`"
      width="400px"
    >
      <div class="weight-edit-dialog">
        <div class="info-row">
          <span class="label">区域编号:</span>
          <span class="value">{{ currentRack?.region_id }}</span>
        </div>
        
        <div class="info-row">
          <span class="label">制冷剂类型:</span>
          <span class="value">{{ currentRack?.refrigerant_type }}</span>
        </div>
        
        <div class="info-row">
          <span class="label">当前重量:</span>
          <span class="value">{{ currentRack?.['Refrigerant weight'] }} kg</span>
        </div>
        
        <div class="edit-row">
          <span class="label">新重量:</span>
          <el-input-number
            v-model="newWeight"
            :min="0"
            :step="1"
            :max="1000"
            controls-position="right"
            size="large"
          />
          <span class="unit">kg</span>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateWeight">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from 'vue';

// 数据服务模块
const DataService = {
  async fetchWeights() {
    try {
      // 从public文件夹获取数据
      const response = await fetch('/weight.json');
      if (!response.ok) {
        throw new Error('Failed to fetch weights');
      }
      return await response.json();
    } catch (error) {
      console.error('Error fetching weights:', error);
    }
  },

  async updateWeight(region_id, newWeight) {
    console.log(`模拟API调用: 更新区域 ${region_id} 的重量为 ${newWeight}kg`);
    // 改为接口时替换为:
    // return await fetch(`/api/weights/${region_id}`, {
    //   method: 'PUT',
    //   body: JSON.stringify({ weight: newWeight })
    // });
    
    // 返回一个成功的Promise模拟更新
    return Promise.resolve({ success: true });
  }
};

export default {
  name: 'WarehouseLayout',
  setup() {
    return {
      dialogVisible: ref(false),
      newWeight: ref(0),
      currentRack: ref(null),
      isLoading: ref(false) // 添加加载状态
    };
  },
  data() {
    return {
      topRacks: [],
      leftRack: {},
      bottomRacks: [],
      refrigerantTypes: ['R32', 'R454B', 'R410A', 'R407C', 'R404A', 'R134A', 'R22', 'R450A', 'R513A', 'R448A', 'R455A', 'R454C', 'R452A', 'R449A', 'R515B', 'R410A', 'R407F', 'R507A', 'R454A'],
      weightsData: [] // 存储从JSON加载的数据
    };
  },
  async mounted() {
    this.isLoading = true;
    try {
      // 从weight.json加载数据
      this.weightsData = await DataService.fetchWeights();
      this.populateRacks();
    } catch (error) {
      console.error('初始化数据失败:', error);
    } finally {
      this.isLoading = false;
    }
  },
  methods: {
    populateRacks() {
      // 创建制冷剂类型到数据的映射
      const typeMap = {};
      this.weightsData.forEach(item => {
        typeMap[item.refrigerant_type] = item;
      });

      // 构建架子数据
      this.topRacks = this.refrigerantTypes.slice(0, 11).map(type => 
        typeMap[type] || { 
          region_id: `T${this.refrigerantTypes.indexOf(type) + 1}`, 
          refrigerant_type: type, 
          'Refrigerant weight': 0 
        }
      );
      
      const leftType = this.refrigerantTypes[11];
      this.leftRack = typeMap[leftType] || { 
        region_id: 'L01', 
        refrigerant_type: leftType, 
        'Refrigerant weight': 0 
      };
      
      this.bottomRacks = this.refrigerantTypes.slice(12).map(type => 
        typeMap[type] || { 
          region_id: `B${this.refrigerantTypes.indexOf(type) + 1}`, 
          refrigerant_type: type, 
          'Refrigerant weight': 0 
        }
      );
    },
    
    selectRack(rack) {
      this.currentRack = rack;
      this.newWeight = rack['Refrigerant weight'];
      this.dialogVisible = true;
    },
    
    async updateWeight() {
      if (this.currentRack) {
        try {
          // 调用数据服务更新重量
          await DataService.updateWeight(this.currentRack.region_id, this.newWeight);
          
          // 更新本地数据
          this.currentRack['Refrigerant weight'] = this.newWeight;
          
          // 同时更新weightsData中的数据，保持一致性
          const itemIndex = this.weightsData.findIndex(item => 
            item.region_id === this.currentRack.region_id
          );
          
          if (itemIndex !== -1) {
            this.weightsData[itemIndex]['Refrigerant weight'] = this.newWeight;
          }
          
          this.dialogVisible = false;
        } catch (error) {
          console.error('更新重量失败:', error);
          this.$message.error('更新重量失败，请重试');
        }
      }
    }
  },
}
</script>

<style scoped>
.warehouse-container { 
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-title {
  color: #303133;
  font-size: 24px;
  margin: 0 0 20px 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.content-wrapper {
  display: flex;
  gap: 20px;
}

.layout-container {
  flex: 2;
  min-height: 500px;
  background-color: #fafafa;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 5px double #dcdfe6;
}

.warehouse-layout {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
}

/* 左侧制冷剂仓库区域 */
.refrigerant-area {
  flex: 6;
  background: #e6f7ff;
  position: relative;
  border-right: 5px double #9cafff; 
  display: flex; 
  flex-direction: column;
  justify-content: space-between;
}

/* 顶部区域 */
.top-rock {
  flex: 1;
  display: flex; 
  align-items: flex-start; 
  justify-content: center;
}

/* 底部区域 */
.bottom-row {
  flex: 4;
  display: flex;
  justify-content: space-between;
}

/* 底部左侧 */
.left-rock {
  flex: 0 0 10%;  /*固定宽度为10%*/
  display: flex;
  justify-content: center;
  align-items: stretch;
  margin: 5px;
}

/* 底部右侧 */
.bottom-area {
  flex: 1;   /*让右侧区域占据剩余空间*/
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.bottom-road {
  flex: 3;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bottom-road-title {
  color: #ccc;
  font-size: 50px;
}

.bottom-rock {
  flex: 1;
  display: flex;
  align-items: flex-end;
  justify-content: space-around;
  width: 100%;
}

/* 架子 */
.rack-row {
  display: flex;
  justify-content: center; 
  margin: 10px 0; /* 垂直间距 */
  height: 90%;
}

.rack {
  margin: 7px;
  padding: 10px;
  border-radius: 2px;
  text-align: center;
  cursor: pointer;
  background-color: #ffda90;
  display: flex; 
  flex-direction: column;
  justify-content: center; 
  align-items: center;
  border: 1px solid #000000;
}

.rack-label {
  margin-bottom: 5px;
  /* font-weight: bold; */
}

.rack-weight {
  margin-top: 5px;
  color: #1e589a;
}

/* 门 */
.main-door{
  width: 15%;
  /* padding: 10px; */
  text-align: center;
  background: #4e80f2; /* 背景颜色 */
  color: white;
  border-radius: 2px;
  margin: 10px;
}
.small-door {
  width: 8%;
  /* padding: 10px; */
  text-align: center;
  background: #4e80f2; /* 背景颜色 */
  color: white;
  border-radius: 2px;
  margin: 10px;
}

/* 右侧废品库 */
.waste-oil-area {
  flex: 1;
  background: #fff8e6;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.waste-oil-content {
  text-align: center;
}
.area-title {
  color: #4d4d4d;
}

/* 弹出框样式 */
.weight-edit-dialog {
  padding: 10px;
}
.info-row {
  display: flex;
  justify-content: left;
  margin-bottom: 15px;
}
.label {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
}
.value {
  color: #555;
  margin-top: 4px;
}
.edit-row {
  display: flex;
  align-items: center;
  margin-top: 15px;
}
.unit {
  margin-left: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

</style>
